package com.cucker.urlforwarder.util;

import java.util.*;

/**
 * Fully Qualified Domain Name 处理
 */
public class FqdnUtil {
    /**
     * 把 Fully Qualified Domain Name 分割为 主机名 和 域名
     *
     * @param fqdn: Fully Qualified Domain Name
     * @param level: 分割多少层作为 主机名
     * @return Map: 格式 {"host": "www", "zone": "qq.com"}
     */
    public static Map<String, String> fqdnSplit(String fqdn, int level) {
        if (fqdn == null) {
            return null;
        }
        fqdn = fqdn.strip();
        if (Objects.equals(fqdn, "")) {
            return null;
        }
        if (level <= 0) {
            return null;
        }
        if (IpAddress.isValidIP(fqdn)) {
            return null;
        }

        if (fqdn.contains(":")) {
            fqdn = fqdn.split(":")[0];
        }

        // fqdn 为 "主机名+域名"
        String[] fqdnArray = fqdn.split("\\.");
        if (fqdnArray.length  <= 1) {
            return null;
        }
        if (fqdnArray.length <= level) {
            return null;
        }

        String host = null, zone = null;
        if (level == 1) {
            host = fqdnArray[0];
            zone = String.join(".", Arrays.copyOfRange(fqdnArray, 1, fqdnArray.length));
        } else {
            host = String.join(".", Arrays.copyOfRange(fqdnArray, 0, level));
            zone = String.join(".", Arrays.copyOfRange(fqdnArray, level, fqdnArray.length));
        }
        Map<String, String> map = new HashMap<>();
        map.put("host", host);
        map.put("zone", zone);

        return map;
    }

    public static Map<String, String> fqdnSplit(String fqdn) {
        return fqdnSplit(fqdn, 1);
    }
}
